package cn.chaos.nio01;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;

public class TCPServerSelector {

    private static final int BUF_SIZE = 256; // 
    private static final int TIMEOUT = 3000; // Wait timeout (milliseconds)
    
    public static void main(String[] args) throws IOException  {
        Selector selector = Selector.open();
        int port = 11111;
        
        ServerSocketChannel listenChannel = ServerSocketChannel.open();
        listenChannel.socket().bind(new InetSocketAddress(port));
        listenChannel.configureBlocking(true);
        listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        
        
        TCPProtocol protocol = new EchoSelectorProtocol(BUF_SIZE);
        
        while (true) {
            if (selector.select(TIMEOUT) == 0) {
                System.out.print(".");
                continue;
            }
            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {
                SelectionKey key = keyIter.next(); 
                
                if (key.isAcceptable()) {
                    protocol.handleAccept(key);
                }
                
                if (key.isReadable()) {
                    protocol.handleRead(key);
                }
                
                if (key.isValid() && key.isWritable()) {
                    protocol.handleWrite(key);
                }
                keyIter.remove();
            }
        }
    }
}
